'use strict';
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
 // let {id} = event
  if(event.name=='readarticle'){
	 return await db.collection('article')
	     .where({
	       _id: event.id
	     }).update({
	       data: {
	       readnum:_.inc(1)
	     }
	   })
  }else if(event.name=='openid'){
	  return event.userInfo;
  }else if(event.name=='upuserdata'){
	  //更新用户数据
	  console.log('aaaa')
	  return await db.collection('user')
	     .where({
	       openid: event.data.openid
	    }).update({
	       data: event.data
	   })
  }else if(event.name=='nearplace'){
	  //最近的地点
	  console.log(event.lng, event.lat)
	  return await db.collection('place').aggregate().geoNear({
			 distanceField: 'distance', 
			 spherical: true,
			 near: db.Geo.Point(event.lng, event.lat),
			  maxDistance:10000
		}).limit(1000).sort({
			'distance':1
		 }).limit(1000).end()
		
  }else if(event.name=='index'){
	  console.log(event.lng, event.lat)
	  //范围内最晚发布
	  return await db.collection('place').aggregate().geoNear({
			 distanceField: 'distance', 
			 spherical: true,
			 near: db.Geo.Point(event.lng, event.lat),
			 maxDistance:100000
		}).limit(100).sort({
			'lasttime':-1
		 }).end()
		
  }else if(event.name=='sendpost'){
		console.log(event.data,'发布消毒信息')
		return await db.collection('place')
		   .where({
		     _id: event.data.placeid
		  }).update({
			  data:{
				list:_.unshift(event.data),
				lastusername:event.data.username,
				lasttime:event.data.time
			  }
		 })
		
  }else{
	  return event
  }
};